package cn.deng.mybatis.binding;


import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.deng.mybatis.session.SqlSession;

/**
 * @author: DengJingWen deng
 * @description:
 * @create: 2025-05-16
 */

public class MapperProxyFactory<T> {

    private final Class<T> mapperInterface;
    private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Map<Method, MapperMethod> getMethodCache() {
        return methodCache;
    }

    // 代理创建对象。如：IUserDao userDao = factory.newInstance(sqlSession);
    @SuppressWarnings("unchecked")
    public T newInstance(SqlSession sqlSession) {
        final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
        // 处理：
        // 1. 使用接口的类加载器
        // 2. 指定要实现的接口数组（这里只有一个接口）
        // 3. 提供一个 InvocationHandler 的实现（这里是 MapperProxy 实例）
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }

}